package com.xinxin.base.util.legacy;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class AesUtil {
    static final int KEY_LENGTH_BYTE = 32;
    static final int TAG_LENGTH_BIT = 128;
    static final byte[] aesKey = "97fcc48cb8a3f0dd656d90c4d621bb8a".getBytes();

    /*public AesUtil(byte[] key) {
        if (key.length != KEY_LENGTH_BYTE) {
            throw new IllegalArgumentException("无效的ApiV3Key，长度必须为32个字节");
        }
        this.aesKey = key;
    }*/

    public static String decryptToString(byte[] associatedData, byte[] nonce, String ciphertext)
            throws GeneralSecurityException, IOException {
        try {
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");

            SecretKeySpec key = new SecretKeySpec(aesKey, "AES");
            GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce);

            cipher.init(Cipher.DECRYPT_MODE, key, spec);
            cipher.updateAAD(associatedData);

            return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), "utf-8");
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw new IllegalStateException(e);
        } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public static void main(String[] args) {
        try {
            String s = decryptToString("transaction".getBytes(), "ojMwrOOGNZem".getBytes(), "kS8LdOUxpjmkoLarfW4TRwC5vx5q9olCWY1LtG0YgYDQS2xotJ2bOW+zSLc5qYiWGSx7sIaSXaFtq66hdLbDj8HFgghN41gNL1ZHzU6wfemAtNfkUH8HBYlquvKxru02XRXfsYwghdYf1xVje9Q3P3XqOyle+tqTB0pOYONjUFxQlfEd/aJe3VlV/VV/cbCYVQVVmjchP5xaxs5TPiOXn1QyIZTlaNz/6RR/YwhZcLn7tBDPcf4ED+KgEGhUFfSWnKQxolEKFSeJLYZ3TLcSbgodZpM9n27W4dukRz7auSpBV8kYejBDeW5HmCY4C/YKm/zIxSaGZL8+dZkWGpxYhHcMRCYpuaSyIb278RTQy0ej0K/z21IcH0ySsbCeYZmDcX1AJHuy9qrqhO36kVJbdLzoeXURdJlE9C82ZVRDAMRZI/2qiySagU1LUjWsYDivUs0CBn69cgSisuEIGsrTrc+UZkPZs5si0p8C0Kw15AvrwcKFyko3/asYh0TMQ3GV3u9zRYb5tE8qiKzcIHbPj4gNum0gzlrkFjKx/h/fLEF95+iwb2plGraboFAoUPj+vdQqopFB9Ko2HArEbxw=");
            System.out.println(s);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
